package com.propertyportal.propertylistfragment;

import java.io.File;
import java.io.FileInputStream;

import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.dropbox.client2.DropboxAPI.Entry;
import com.propertyportal.manageproperty.ManageProperty;
import com.propertyportal.manageproperty.R;

public class AddImage extends SherlockFragment{
    public final static String ARG_POSITION = "position";
    private LinearLayout add_image_layout;
    private LinearLayout add_panorama_layout;
    private LinearLayout hidden1;
    private LinearLayout hidden2;
    private boolean flag=true;
    private boolean flag2=true;
    private Animation inAnimation;
    private EditText filename1;
    private EditText filename2;
    
    
    private Button upload1;
    private Button upload2;
    private ImageView browse1;
    private ImageView browse2;
    private ImageView camera;
    private TextView validate1,validate2,title,price,address;
    private final int SELECT_PICTURE1 = 1;
    private final int SELECT_PICTURE2 = 2;
    private final int CAMERA_REQUEST=3;
    /*final static private String APP_KEY = "mcret8mq7n203re";
    final static private String APP_SECRET = "o9avsnzk98ajwxh";
    final static private AccessType ACCESS_TYPE = AccessType.APP_FOLDER;
   
    final static private String ACCOUNT_PREFS_NAME = "prefs";
    final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
    final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";

    private DropboxAPI<AndroidAuthSession> mDBApi;
    private SharedPreferences session;*/
    private boolean isFirstUpload;
    private SherlockFragmentActivity fa;
   
   
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            View view=inflater.inflate(R.layout.add_image,container, false);
            fa=(SherlockFragmentActivity)super.getActivity();
            add_image_layout=(LinearLayout)view.findViewById(R.id.add_image_layout);
            add_panorama_layout=(LinearLayout)view.findViewById(R.id.add_panorama_layout);
            hidden1=(LinearLayout)view.findViewById(R.id.hidden);
            hidden2=(LinearLayout)view.findViewById(R.id.hidden2);
            filename1=(EditText)view.findViewById(R.id.filename1);
            filename2=(EditText)view.findViewById(R.id.filename2);
            filename1.setEnabled(false);
            filename2.setEnabled(false);
            upload1=(Button)view.findViewById(R.id.upload_image);
            upload2=(Button)view.findViewById(R.id.upload_panorama);
            browse1=(ImageView)view.findViewById(R.id.browse);
            browse2=(ImageView)view.findViewById(R.id.browse2);
            camera=(ImageView)view.findViewById(R.id.camera);
            validate1=(TextView)view.findViewById(R.id.validation1);
            validate2=(TextView)view.findViewById(R.id.validation2);
           
            title=(TextView)view.findViewById(R.id.titleI);
            price=(TextView)view.findViewById(R.id.priceI);
            address=(TextView)view.findViewById(R.id.addressI);
           
            inAnimation = (Animation) AnimationUtils.loadAnimation(getActivity(),android.R.anim.fade_in );
            //for dropbox image
           // session=PreferenceManager.getDefaultSharedPreferences(getActivity());
           
            //AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
            /*AndroidAuthSession session = buildSession();
           
            mDBApi = new DropboxAPI<AndroidAuthSession>(session);*/
           
           
            add_image_layout.setOnClickListener(new OnClickListener() {
                   
                    @Override
                    public void onClick(View v) {
                            // TODO Auto-generated method stub
                            if(flag){
                                    hidden1.setVisibility(View.VISIBLE);
                                    hidden1.setAnimation(inAnimation);
                                    flag=false;
                            }
                            else{
                                    hidden1.setVisibility(View.GONE);
                                    flag=true;
                            }
                            isFirstUpload=true;
                    }
            });
            add_panorama_layout.setOnClickListener(new OnClickListener() {
                   
                    @Override
                    public void onClick(View v) {
                            // TODO Auto-generated method stub
                            if(flag2){
                                    hidden2.setVisibility(View.VISIBLE);
                                    hidden1.setAnimation(inAnimation);
                                    flag2=false;
                            }
                            else{
                                    hidden2.setVisibility(View.GONE);
                                    flag2=true;
                            }
                            isFirstUpload=false;
                    }
            });
            //upload image
            upload1.setOnClickListener(new OnClickListener() {
                   
                    @Override
                    public void onClick(View v) {
                            // TODO Auto-generated method stub
                            if (!filename1.getText().toString().equals("")) {
                                    if (PropertyList.mDBApi.getSession().isLinked()) {
                                            //uploadImage(filename1.getText().toString());
                                            new SaveImage().execute(filename1.getText().toString());
                                            filename1.setText("");
                                    } else {
                                            PropertyList.mDBApi.getSession().startAuthentication(getActivity());
                                    }
                            } else {
                                    validate1.setVisibility(View.VISIBLE);
                                    validate1.setText("Cannot Be Empty!");
                            }
                        
                    }
            });
            //upload panorama
            upload2.setOnClickListener(new OnClickListener() {
                   
                    @Override
                    public void onClick(View v) {
                            // TODO Auto-generated method stub
                            //mDBApi.getSession().startAuthentication(getActivity());
                            if(!filename2.getText().toString().equals("")){
                                    if (PropertyList.mDBApi.getSession().isLinked()) {
                                            //uploadImage(filename2.getText().toString());
                                            new SaveImage().execute(filename2.getText().toString());
                                            filename2.setText("");
                                    } else {
                                            PropertyList.mDBApi.getSession().startAuthentication(getActivity());
                                    }
                            }else{
                            	 validate2.setVisibility(View.VISIBLE);
                                 validate2.setText("Cannot Be Empty!"); 
                            }
                            isFirstUpload=false;
                           
                    }
            });
            //browse image
            browse1.setOnClickListener(new OnClickListener() {
                   
                    @Override
                    public void onClick(View v) {
                            // TODO Auto-generated method stub
                           Intent intent = new Intent();
                        intent.setType("image/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(Intent.createChooser(intent,
                                "Select Picture"), SELECT_PICTURE1);
                           
                    }
            });
            //browse panorama image
            browse2.setOnClickListener(new OnClickListener() {
                   
                    @Override
                    public void onClick(View v) {
                            // TODO Auto-generated method stub
                             Intent intent = new Intent();
                             
                        intent.setType("image/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(Intent.createChooser(intent,
                                "Select Picture"), SELECT_PICTURE2);
                    }
            });
            //go to camera
            camera.setOnClickListener(new OnClickListener() {
                   
                    @Override
                    public void onClick(View v) {
                            // TODO Auto-generated method stub
                            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                            startActivityForResult(cameraIntent, CAMERA_REQUEST);
                    }
            });
            return view;
    }
    public void onStart() {
            // TODO Auto-generated method stub
            super.onStart();
            Bundle args = getArguments();
            if (args != null) {
                    displayData(args.getInt(ARG_POSITION));
            }
    }
    @Override
    public void onResume() {
            // TODO Auto-generated method stub
            super.onResume();
/*              if(mDBApi.getSession().isLinked()){
                    Toast.makeText(getActivity(), "Done Auth", Toast.LENGTH_SHORT).show();
            }
            else {*/
                   /* if (mDBApi.getSession().authenticationSuccessful()) {
                            AccessTokenPair tokens;
                            try {
                                    // Required to complete auth, sets the access token on the
                                    // session
                                    mDBApi.getSession().finishAuthentication();

                                    tokens = mDBApi.getSession()
                                                    .getAccessTokenPair();
                                    storeKeys(tokens.key, tokens.secret);
                                    System.out.println(tokens);
                            } catch (IllegalStateException e) {
                                    Log.i("DbAuthLog", "Error authenticating", e);
                            }
          }*/
            //}
    }
    public void displayData(int position){
            title.setText(PropertyList.property.get(position).getName());
            address.setText(PropertyList.property.get(position).getAddress());
            price.setText(PropertyList.property.get(position).getPrice());
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
            // TODO Auto-generated method stub
            switch (requestCode) {
           
            case SELECT_PICTURE1:
                    if (resultCode == ManageProperty.RESULT_OK) {
                            if (data != null) {
                                    final Uri uri = data.getData();

                                    try {
                                            filename1.setText(getRealPathFromURI(uri));

                                    } catch (Exception e) {
                                            Log.e("FileSelectorTestActivity",
                                                            "File select error CREATEACCOUNT", e);
                                    }
                            }

                    }
                    break;
            case SELECT_PICTURE2:
                    if (resultCode == ManageProperty.RESULT_OK) {
                            if (data != null) {
                                    final Uri uri = data.getData();

                                    try {
                                            filename2.setText(getRealPathFromURI(uri));

                                    } catch (Exception e) {
                                            Log.e("FileSelectorTestActivity",
                                                            "File select error CREATEACCOUNT", e);
                                    }
                            }

                    }
                    break;
           
           
            }
   
            super.onActivityResult(requestCode, resultCode, data);
    }
    public String getRealPathFromURI(Uri contentUri) {
            String[] proj = { MediaStore.Images.Media.DATA };
            Cursor cursor = getActivity().getContentResolver().query(contentUri, proj, null,
                            null, null);
            int column_index = cursor
                            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
    }
    public void uploadImage(String filename){
            try{
                    File file = new File(filename);
                    FileInputStream inputStream = new FileInputStream(file);
                    //String newFolder=mDBApi.createFolder("sample").toString();
                    Entry response = PropertyList.mDBApi.putFile(PropertyList.property.get(ManageProperty.clickposition).getName()+"/"+file.getName(), inputStream,
                            file.length(), null, null);
                    Log.i("DbExampleLog", "The uploaded file's rev is: " + response.rev);

                    }catch(Exception e){
                           
                    }
    }
    /* private String[] getKeys() {
     SharedPreferences prefs = getActivity().getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
     String key = prefs.getString(ACCESS_KEY_NAME, null);
     String secret = prefs.getString(ACCESS_SECRET_NAME, null);
     if (key != null && secret != null) {
            String[] ret = new String[2];
            ret[0] = key;
            ret[1] = secret;
            return ret;
     } else {
            return null;
     }
}
     private void storeKeys(String key, String secret) {
     // Save the access key for later
     SharedPreferences prefs = getActivity().getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
     Editor edit = prefs.edit();
     edit.putString(ACCESS_KEY_NAME, key);
     edit.putString(ACCESS_SECRET_NAME, secret);
     edit.commit();
}
    private AndroidAuthSession buildSession() {
    AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
    AndroidAuthSession session;

    String[] stored = getKeys();
    if (stored != null) {
           AccessTokenPair accessToken = new AccessTokenPair(stored[0], stored[1]);
           session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE, accessToken);
    } else {
           session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE);
    }

    return session;
}  */
    private class SaveImage extends AsyncTask<String, Void, Void> {

            private ProgressDialog dialog = new ProgressDialog(fa);

            protected void onPreExecute() {

                    dialog.setMessage("Saving...");
                    dialog.show();
            }

            @Override
            protected Void doInBackground(final String... text) {

                    try {
                     
                     uploadImage(text[0]);

                    } catch (Exception e) {
                            Log.e("", "wala jud ma add", e);
                    }
                    return null;
            }

            protected void onPostExecute(Void result) {
                    if (this.dialog != null) {
                            this.dialog.dismiss();
                    }
                    if(isFirstUpload){
                    	validate1.setVisibility(View.VISIBLE);
                    	validate1.setText("Successfully Added!");
                    }
                    else{
                    	validate2.setVisibility(View.VISIBLE);
                    	validate2.setText("Successfully Added!");
                    }
            }

    }

}
